﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.Engine
{
    public class CameraModule : Jemgine.Engine.Module
    {
        public Jemgine.Data.EntityRecord Focus { get; set; }
        public float DestinationZoom { get; set; }
        public Jemgine.Engine.Renderer.Camera Camera = null;
        public bool AlignWithFocus { get; set; }

        public CameraModule()
        {
            AlignWithFocus = true;
            DestinationZoom = 8;
        }

        public void Init(Vector2 ViewDims, float Zoom)
        {
            Camera = new Renderer.Camera(ViewDims);
            Camera.zoom = Zoom;
            DestinationZoom = Zoom;
        }

        public override void BeginSimulation()
        {
            Focus = null;
            base.BeginSimulation();
        }

        public override void Update(float ElapsedSeconds)
        {
            if (AlignWithFocus && Focus != null)
            {
                Vector2 CamDelta = Focus.Position - -Camera.offset;

                CamDelta *= 0.1f;
                Camera.offset -= CamDelta;

                float AngleDelta = Jemgine.Math.Angle.Delta(Jemgine.Math.Angle.Normalize(-Camera.rotation),
                    Jemgine.Math.Angle.Normalize(Focus.Angle));
                Camera.rotation = Jemgine.Math.Angle.Normalize(Camera.rotation - (AngleDelta * 0.1f));
            }

            float ZoomDelta = DestinationZoom - Camera.zoom;
            ZoomDelta *= 0.1f;
            Camera.zoom += ZoomDelta;
        }

        public void TeleportCamera(Vector2 Where, float Zoom, float Angle)
        {
            Sim.CameraModule.Camera.offset = Where;
            Sim.CameraModule.Camera.zoom = Zoom;
            DestinationZoom = Zoom;
            Sim.CameraModule.Camera.rotation = Angle;
        }

        public Vector2 TransformScreenToWorld(Vector2 V)
        {
            return Camera.UnProject(V);
        }

        public Vector2 TransformScreenVelocityToWorld(Vector2 V)
        {
            return Vector2.Transform(V, Matrix.CreateRotationZ(-Camera.rotation));

        }
    }
}
